package com.ibeeking.found.content.c.rest.service.impl;

import com.ibeeking.found.common.constants.WxOpenServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxOpenAppTypeEnum;
import com.ibeeking.found.common.response.ResponseCodeEnum;
import com.ibeeking.found.common.utils.DataUtils;

import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;

import com.ibeeking.found.content.c.rest.config.prop.RedisProperties;
import com.ibeeking.found.content.c.rest.service.IWxOpenService;
import com.ibeeking.found.content.service.common.constants.RedisKeyConstant;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.exception.DataNotExistException;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.open.api.WxOpenComponentService;
import me.chanjar.weixin.open.api.WxOpenMaService;
import me.chanjar.weixin.open.api.WxOpenMpService;
import me.chanjar.weixin.open.api.WxOpenService;
import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage;
import me.chanjar.weixin.open.bean.WxOpenAuthorizerAccessToken;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 禁止在此类加其他业务方法
 *
 * @ClassName WxMpService
 * @Description
 * @Author ibeeking
 * @Date 2020-12-30 10:29
 **/
@Service
@EnableConfigurationProperties({RedisProperties.class})
public class WxOpenServiceImpl implements IWxOpenService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //30分钟
    private static final Long TIME = 30 * 60 *1000L;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private RedisProperties redisProperties;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    private OpenConfigDTO queryOpenConfigOfWxOpen() {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_OPEN.getCode());
        query.setSubType(WxOpenAppTypeEnum.WECHAT_OPEN_APP_TYPE_TP.getCode());
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        OpenConfigDTO openConfigDTO = responseResult.getData();
        return openConfigDTO;
    }

    @Override
    public OpenAuthDTO queryWxOpenAuthByTenantId(Long tenantId,Integer configType, Integer configSubType, Integer appType) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setConfigType(configType);
        query.setConfigSubType(configSubType);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), responseResult.getMsg());
        return responseResult.getData();
    }

    /**
     * 获取公众号服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxOpenMpService getWxOpenMpService(Long tenantId) {
        WxOpenService wxOpenService = SpringBeanUtil.getBean(WxOpenService.class);
        if(wxOpenService == null) throw new BusinessException("get WxOpenService service error!");
        WxOpenInRedisConfigStorage redisConfigStorage = null;
        String configStoragekey = RedisKeyConstant.WX_OPEN_CONFIG_KEY.concat(tenantId.toString()).concat(":").concat(WxOpenServiceTypeConstant.APPID_TYPE_MP.toString());
        String appId = null;
        Object objConfigStorage = redisUtils.get(configStoragekey);
        if(ObjectUtils.isEmpty(objConfigStorage)) {
            redisConfigStorage = new WxOpenInRedisConfigStorage(redisProperties.getJedisPool(), "wx:open");
            OpenConfigDTO wxOpenConfig = queryOpenConfigOfWxOpen();
            if(wxOpenConfig == null) throw new BusinessException("没有读取到开放平台配置参数!");
            OpenConfigOfExtend openConfigOfExtend = wxOpenConfig.getOpenConfigOfExtend();
            if(openConfigOfExtend == null) throw new BusinessException("没有读取到开放平台配置参数!");
            OpenConfigOfWxOpen openConfigOfWxOpen = openConfigOfExtend.getOpenConfigOfWxOpen();
            if(openConfigOfWxOpen == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthDTO openAuthDTO = queryWxOpenAuthByTenantId(tenantId, wxOpenConfig.getType(), wxOpenConfig.getSubType(), WxOpenServiceTypeConstant.APPID_TYPE_MP);
            if(openAuthDTO == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend == null) throw new BusinessException("没有读取到开放平台配置权限!");
            appId = openAuthDTO.getAppId();
            OpenAuthOfWxOpen openAuthOfWxOpen = openAuthOfExtend.getOpenAuthOfWxOpen();
            if(openAuthOfWxOpen == null) throw new BusinessException("没有读取到开放平台配置权限!");
            redisConfigStorage.setComponentAppId(wxOpenConfig.getComponentAppId());
            redisConfigStorage.setComponentAppSecret(wxOpenConfig.getOpenAppSecret());
            redisConfigStorage.setComponentToken(wxOpenConfig.getComponentMsgToken());
            redisConfigStorage.setComponentAesKey(wxOpenConfig.getComponentMsgAesKey());
            redisConfigStorage.setComponentVerifyTicket(openConfigOfWxOpen.getComponentVerifyTicket());
            redisConfigStorage.setComponentAccessToken(openConfigOfWxOpen.getComponentAccessToken());
            redisConfigStorage.updateAuthorizerRefreshToken(appId, openAuthOfWxOpen.getAuthorizerRefreshToken());
            WxOpenAuthorizerAccessToken authorizerAccessToken = new WxOpenAuthorizerAccessToken();
            authorizerAccessToken.setAuthorizerRefreshToken(openAuthOfWxOpen.getAuthorizerRefreshToken());
            authorizerAccessToken.setAuthorizerAccessToken(openAuthOfWxOpen.getAuthorizerAccessToken());
            redisConfigStorage.updateAuthorizerAccessToken(appId,authorizerAccessToken);
            redisUtils.set(configStoragekey, redisConfigStorage, 1000);
        }else{
            redisConfigStorage = (WxOpenInRedisConfigStorage) objConfigStorage;
        }
        wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
        WxOpenComponentService wxOpenComponentService = wxOpenService.getWxOpenComponentService();
        WxOpenMpService wxOpenMpService = wxOpenComponentService.getWxMpServiceByAppid(appId);
        if (null == wxOpenMpService) {
            throw new DataNotExistException("获取小程序服务WxMaService失败");
        }
        return wxOpenMpService;
    }

    /**
     * 获取当前小程序服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxOpenMaService getWxOpenMaService(Long tenantId) {
        WxOpenService wxOpenService = SpringBeanUtil.getBean(WxOpenService.class);
        if(wxOpenService == null) throw new BusinessException("get WxOpenService service error!");
        WxOpenInRedisConfigStorage redisConfigStorage = null;
        String configStoragekey = RedisKeyConstant.WX_OPEN_CONFIG_KEY.concat(tenantId.toString()).concat(":").concat(WxOpenServiceTypeConstant.APPID_TYPE_MINI.toString());
        String appId = null;
        Object objConfigStorage = redisUtils.get(configStoragekey);
        if(ObjectUtils.isEmpty(objConfigStorage)) {
            redisConfigStorage = new WxOpenInRedisConfigStorage(redisProperties.getJedisPool(), "wx:open");
            OpenConfigDTO wxOpenConfig = queryOpenConfigOfWxOpen();
            if(wxOpenConfig == null) throw new BusinessException("没有读取到开放平台配置参数!");
            OpenConfigOfExtend openConfigOfExtend = wxOpenConfig.getOpenConfigOfExtend();
            if(openConfigOfExtend == null) throw new BusinessException("没有读取到开放平台配置参数!");
            OpenConfigOfWxOpen openConfigOfWxOpen = openConfigOfExtend.getOpenConfigOfWxOpen();
            if(openConfigOfWxOpen == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthDTO openAuthDTO = queryWxOpenAuthByTenantId(tenantId, wxOpenConfig.getType(), wxOpenConfig.getSubType(), WxOpenServiceTypeConstant.APPID_TYPE_MINI);
            if(openAuthDTO == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend == null) throw new BusinessException("没有读取到开放平台配置权限!");
            appId = openAuthDTO.getAppId();
            OpenAuthOfWxOpen openAuthOfWxOpen = openAuthOfExtend.getOpenAuthOfWxOpen();
            if(openAuthOfWxOpen == null) throw new BusinessException("没有读取到开放平台配置权限!");
            redisConfigStorage.setComponentAppId(wxOpenConfig.getComponentAppId());
            redisConfigStorage.setComponentAppSecret(wxOpenConfig.getOpenAppSecret());
            redisConfigStorage.setComponentToken(wxOpenConfig.getComponentMsgToken());
            redisConfigStorage.setComponentAesKey(wxOpenConfig.getComponentMsgAesKey());
            redisConfigStorage.setComponentVerifyTicket(openConfigOfWxOpen.getComponentVerifyTicket());
            redisConfigStorage.setComponentAccessToken(openConfigOfWxOpen.getComponentAccessToken());
            redisConfigStorage.updateAuthorizerRefreshToken(appId, openAuthOfWxOpen.getAuthorizerRefreshToken());
            WxOpenAuthorizerAccessToken authorizerAccessToken = new WxOpenAuthorizerAccessToken();
            authorizerAccessToken.setAuthorizerRefreshToken(openAuthOfWxOpen.getAuthorizerRefreshToken());
            authorizerAccessToken.setAuthorizerAccessToken(openAuthOfWxOpen.getAuthorizerAccessToken());
            redisConfigStorage.updateAuthorizerAccessToken(appId,authorizerAccessToken);
            redisUtils.set(configStoragekey, redisConfigStorage, 1000);
        }else{
            redisConfigStorage = (WxOpenInRedisConfigStorage) objConfigStorage;
        }
        wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
        WxOpenComponentService wxOpenComponentService = wxOpenService.getWxOpenComponentService();
        WxOpenMaService wxOpenMaService = wxOpenComponentService.getWxMaServiceByAppid(appId);
        if (null == wxOpenMaService) {
            throw new DataNotExistException("获取小程序服务WxMaService失败");
        }
        return wxOpenMaService;
    }


    private WxOpenServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }
}